package freespiritsocial.io.user.viewmodel

import androidx.lifecycle.asLiveData
import freespiritsocial.io.user.data.model.bean.Tag
import freespiritsocial.io.user.network.apiService
import kotlinx.coroutines.flow.*
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.livedata.StringLiveData
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.util.loge

class SearchTagViewModel: BaseViewModel() {
    val searchText = StringLiveData()

    private val _stateFlow = MutableStateFlow<String>("")

    val searchResultNetWork =
        // 避免在单位时间内，快输入造成大量的请求
        _stateFlow.debounce(1000)
            .flatMapLatest {
                it.loge("csw")
                if (it.isEmpty()) {
                    emptyFlow()
                } else
                    apiService.getTagList(hashMapOf("keyword" to searchText.value)).data!!.asFlow()
            }.catch {
                this.toString().loge("catch")
            }.asLiveData()


    fun search() {
        _stateFlow.value = searchText.value
    }

}